package org.ruoyi.graph3.controller;
 
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Optional;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.stereotype.Component;

@Component
public class KimiClient {
    private static final String BASE = "https://api.moonshot.cn/v1";
    private final String apiKey = "sk-aHYYV1SARscItye5QQRRNbXij4fy65Ee7pNZlC9gsSQnUKXA";
    private final OkHttpClient http = new OkHttpClient();
    private final ObjectMapper om = new ObjectMapper();
 
    // 上传文件并解析内容
    public String uploadAndExtract(File file) throws IOException {
        // 1. 构建文件上传请求
        Request upReq = new Request.Builder()
                .url(BASE + "/files")
                .addHeader("Authorization", "Bearer " + apiKey)
                .post(createMultipartBody(file))
                .build();
 
        // 2. 执行请求并获取文件ID
        String fileId = extractFileId(upReq);
        
        // 3. 等待解析完成（官方异步处理）
        awaitParsingCompletion();
        
        // 4. 获取解析后的文本内容
        return fetchFileContent(fileId);
    }
 
    private MultipartBody createMultipartBody(File file) {
        return new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(file, MediaType.parse("application/octet-stream")))
                .build();
    }
 
    private String extractFileId(Request request) throws IOException {
        try (Response response = http.newCall(request).execute()) {
            JsonNode json = om.readTree(response.body().string());
            return json.get("id").asText();
        }
    }
 
    private void awaitParsingCompletion() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("文件解析被中断", e);
        }
    }
 
    private String fetchFileContent(String fileId) throws IOException {
        Request getReq = new Request.Builder()
                .url(BASE + "/files/" + fileId + "/content")
                .addHeader("Authorization", "Bearer " + apiKey)
                .build();
        
        try (Response response = http.newCall(getReq).execute()) {
            return response.body().string();
        }
    }
 
    // 构建思维导图
    public String buildMindMap(String fullText) throws IOException {
        String prompt = String.join("\n", 
            "你是一位知识工程师。",
            "请根据以下文档的目录或正文标题，生成思维导图：",
            "- 用 Mermaid mindmap 语法输出",
            "- 只保留层级关系，不要冗余文字",
            "- 最多 3 层深度",
            "",
            "文档内容：",
            fullText
        );
 
        String json = om.writeValueAsString(Collections.singletonMap(
            "model", "moonshot-v1-8k"
        ));
 
        Request req = new Request.Builder()
                .url(BASE + "/chat/completions")
                .addHeader("Authorization", "Bearer " + apiKey)
                .post(RequestBody.create(json, MediaType.parse("application/json")))
                .build();
 
        try (Response response = http.newCall(req).execute()) {
            JsonNode jsonResponse = om.readTree(response.body().string());
            return Optional.ofNullable(jsonResponse)
                    .map(node -> node.get("choices"))
                    .filter(choices -> choices.size() > 0)
                    .map(choices -> choices.get(0).get("message").get("content"))
                    .map(JsonNode::asText)
                    .orElseThrow(() -> new IOException("无法解析响应内容"));
        }
    }
}